const Base = require('./base.js');

module.exports = class extends Base {
  async loginByWeixinAction() {
    const code = this.post('code');
    const fullUserInfo = this.post('userInfo');
    const clientIp = this.ctx.ip;

    // 解释用户数据
    const userInfo = await this.service('weixin', 'api').login(
      code,
      fullUserInfo
    );
    if (think.isEmpty(userInfo)) {
      return this.fail('登录失败');
    }

    // 根据openid查找用户是否已经注册
    let userId = await this.model('user')
      .where({ weixin_openid: userInfo.openId })
      .getField('id', true);
    if (think.isEmpty(userId)) {
      // 注册
      console.log(this.post('shareuser'))
      userId = await this.model('user').add({
        username: '微信用户' + think.uuid(6),
        password: '',
        register_time: parseInt(new Date().getTime() / 1000),
        register_ip: clientIp,
        mobile: '',
        weixin_openid: userInfo.openId,
        avatar: userInfo.avatarUrl || '',
        gender: userInfo.gender || 1, // 性别 0：未知、1：男、2：女
        nickname: userInfo.nickName,
        user_level_id: 1,
        proxy_id:this.post('shareuser')>0?"":this.post('proxyid')||0,
        shareuser_id:this.post('shareuser')
      });
      if (userId > 0) {
        const registercount = await this.model('proxy').where({ id: this.post('proxyid') }).increment('register_total', 1)
      }
    }

    // 查询用户信息
    const newUserInfo = await this.model('user')
      .field([
        'id',
        'username',
        'nickname',
        'gender',
        'avatar',
        'birthday',
        'credit',
        'balance',
        'mobile',
        'video_qrcode',
        'product_qrcode'
      ])
      .where({ id: userId })
      .find();
    newUserInfo.coupon = await this.model('user_coupon')
      .where({ user_id: userId })
      .select();
    // 更新登录信息
    const updateinfo = await this.model('user')
      .where({ id: userId })
      .update({
        last_login_time: parseInt(new Date().getTime() / 1000),
        last_login_ip: clientIp
      });
    if (updateinfo == 0) {
      return this.fail(400, '登录失败1');
    }
    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create({ user_id: userId });

    if (think.isEmpty(newUserInfo) || think.isEmpty(sessionKey)) {
      return this.fail('登录失败2');
    }

    return this.success({ token: sessionKey, userInfo: newUserInfo });
  }

  async loginAction() {
    const mobile = this.post('mobile');
    const password = this.post('password');

    const user = await this.model('user')
      .where({ mobile: mobile })
      .find();
    if (think.isEmpty(user)) {
      return this.fail(400, '用户名不正确');
    }
    if (think.md5(password + '' + user.password_salt) !== user.password) {
      return this.fail(400, '密码不正确');
    }

    // 更新登录信息
    await this.model('user')
      .where({ id: user.id })
      .update({
        last_login_time: parseInt(Date.now() / 1000),
        last_login_ip: this.ctx.ip
      });

    const TokenSerivce = this.service('token', 'user');
    const sessionKey = await TokenSerivce.create({
      user_id: user.id
    });

    if (think.isEmpty(sessionKey)) {
      return this.fail('登录失败');
    }

    const userInfo = {
      id: user.id,
      nickname: user.nickname,
      introduction: 'I am a super useristrator',
      avatar: user.avatar,
      gender: user.gender,
      level: user.user_level_id,
      credit: user.credit,
      balance: user.balance
      // user_role_id: user.user_role_id,
      // roles: user.user_role_id == 0 ? ['user'] : ['editor']
    };
    userInfo.coupon = await this.model('user_coupon')
      .where({ user_id: user.id })
      .select();
    return this.success({
      token: sessionKey,
      userInfo: userInfo
    });
  }

  async registerAction() {
    const mobile = this.post('mobile');
    const password = this.post('password');
    const password_salt = Math.random()
      .toString(36)
      .slice(-8);
    const user = await this.model('user')
      .where({ mobile: mobile })
      .find();
    if (!think.isEmpty(user)) {
      return this.fail(400, '用户已存在');
    }
    if (think.isEmpty(password)) {
      return this.fail(400, '请输入密码');
    }
    const res = await this.model('user').add({
      username: mobile,
      mobile: mobile,
      nickname: mobile,
      password: think.md5(password + '' + password_salt),
      register_time: parseInt(Date.now() / 1000),
      last_login_ip: this.ctx.ip,
      password_salt: password_salt,
      proxy_id: this.post('proxyid')
    });

    if (res > 0) {
      const TokenSerivce = this.service('token', 'user');
      const sessionKey = await TokenSerivce.create({
        user_id: res
      });

      if (think.isEmpty(sessionKey)) {
        return this.fail('登录失败');
      }
      const userInfo = await this.model('user')
        .where({ id: res })
        .find();
      return this.success({
        token: sessionKey,
        userInfo: userInfo
      });
    }
  }
  async logoutAction() {
    if (this.ctx.header['x-nideshop-token']) {
      this.ctx.header['x-nideshop-token'] = '';
    }
    return this.success('退出登录');
  }
};
